package com.jiehoo.utils;

import java.lang.reflect.*;
import java.util.*;
import java.io.*;

public class ClassUtil {

	public static String[] getMethods(String className) {
		String methodNames[];
		try {
			Class<?> c = Class.forName(className);
			Method methods[] = c.getMethods();
			methodNames = new String[methods.length];
			for (int i = 0; i < methods.length; i++) {
				methodNames[i] = methods[i].toString();
			}
			return methodNames;
		}

		catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String[] getDeclaredMethods(String className) {
		String methodNames[];
		try {
			Class<?> c = Class.forName(className);
			Method methods[] = c.getDeclaredMethods();
			methodNames = new String[methods.length];
			for (int i = 0; i < methods.length; i++) {
				methodNames[i] = methods[i].toString();
			}
			return methodNames;
		}

		catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean isSameClassType(Object[] objects) {
		if (objects.length == 1) {
			return true;
		}
		Class<?> c = objects[0].getClass();
		for (int i = 1; i < objects.length; i++) {
			if (!c.equals(objects[i].getClass())) {
				return false;
			}
		}
		return true;
	}

	public static boolean isSameClassType(Object[] objects, Class<?> c) {
		if (objects.length == 1) {
			return true;
		}
		for (int i = 1; i < objects.length; i++) {
			if (!c.equals(objects[i].getClass())) {
				return false;
			}
		}
		return true;
	}

	public static boolean isSubclass(Class<?> c, Class<?> child) {
		try {
			if (c.isInstance(child.newInstance())) {
				return true;
			}
			return false;
		} catch (IllegalAccessException e) {
			return false;
		} catch (InstantiationException ie) {
			return false;
		} catch (Exception oe) {
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	public static TreeSet<String> getAllClassname() {
		TreeSet<String> classnameSet = new TreeSet<String>();
		ObjectInputStream p = null;
		try {
			InputStream istream = ClassUtil.class
					.getResourceAsStream("allclassname.treeset");
			p = new ObjectInputStream(istream);
			classnameSet = (TreeSet<String>) p.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (p != null) {
				try {
					p.close();
				} catch (IOException e) {

				}
			}
		}
		return classnameSet;
	}

}